<template>
  <div class="copy-modal-wrapper">
    <a-modal
      :width="620"
      :title="operateType == 'fromOther' ? '从其他门店复制配置' : '复制配置到其他门店'"
      @cancel="close"
      :visible="visible"
    >
      <div class="copy-wrapper">
        <a-tree
          v-if="treeData.length > 0"
          show-line
          blockNode
          v-model:selected-keys="selectedKeys"
          default-expand-all
          :multiple="multiple"
          :data="treeData"
        >
          <template #extra="nodeData">
            <div class="icon-check" v-if="selectedKeys.includes(nodeData.id)">
              <IconCheck style="font-size: 16px" />
            </div>
          </template>
          <template #switcher-icon="node, { isLeaf }">
            <!-- 非叶节点 -->
            <icon-caret-down v-if="!isLeaf" />
            <template v-if="isLeaf">
              <!-- 机构 -->
              <icon-user-group v-if="node.orgType == 2" />
              <!-- 门店 -->
              <icon-home v-else />
            </template>
          </template>
        </a-tree>
      </div>
      <template #footer>
        <a-button @click="close">关闭</a-button>
        <a-button type="primary" @click="handleOk">确认</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup name="MerchantStoreServiceConfigCopyModal">
  import { ref, inject, h } from 'vue'
  import { Notification, Message, Modal } from '@arco-design/web-vue'
  import { getSelectAuthList, siteDetailByOrg, batchSaveConfig } from '@/api/asset/site'
  const props = defineProps({
    configTypePropStr: String,
  })
  // 接收父组件
  const form = inject('form')
  const visible = ref(false)
  // 操作类型分为 fromOther（从其他门店复制） 和 copyTo（复制到其他门店）
  const multiple = ref(false)
  let operateType = ref('fromOther')
  const open = (type) => {
    operateType.value = type
    multiple.value = type == 'fromOther' ? false : true
    visible.value = true
    getTreeDataFn()
  }
  const close = () => {
    visible.value = false
    selectedKeys.value = []
  }
  const handleOk = () => {
    if (selectedKeys.value.length > 0) {
      let content1 = ''
      let content2 = ''
      if (operateType.value == 'fromOther') {
        content1 = '请确认是否使用已选门店的配置？'
        content2 = '本门店配置将会被覆盖'
      } else {
        content1 = '请确认是否将本门店配置复制到其他门店？'
        content2 = '其他门店配置将会被覆盖'
      }
      Modal.confirm({
        title: '提示',
        simple: true,
        content: () => {
          return h('div', {}, [h('span', {}, content1), h('span', { style: { color: 'red' } }, content2)])
        },
        onOk: () => {
          // 从其他门店复制
          if (operateType.value == 'fromOther') {
            const param = {
              id: selectedKeys.value[0],
            }
            siteDetailByOrg(param).then((res) => {
              if (res.code == 200) {
                const result = res.result
                // 获取到结果之后，将当前的结果覆盖
                form.value[props.configTypePropStr] = result[props.configTypePropStr] || {}

                Notification.success({
                  title: '提示',
                  content: '操作成功',
                })
                close()
              }
            })
          } else {
            // 打开复制配置弹窗
            const config = form.value[props.configTypePropStr]
            const param = {
              siteOrgIdList: selectedKeys.value,
              ...config,
            }
            batchSaveConfig(param).then((res) => {
              if (res.code == 200) {
                Notification.success({
                  title: '提示',
                  content: '操作成功',
                })
                close()
              }
            })
          }
        },
      })
    } else {
      Message.error('请先选择门店!')
    }
  }
  const selectedKeys = ref([])
  const treeData = ref([])
  const getTreeDataFn = () => {
    getSelectAuthList().then((res) => {
      if (res.code == 200) {
        const result = res.result.map((e) => {
          e.key = e.id
          e.title = e.orgName
          e.value = e.id
          e.label = e.orgName
          e.children = [] //创建子级
          e.disabled = e.orgType != 3 || !e.authFlag
          return e
        })
        treeData.value = setTreeData(result)
      }
    })
  }
  // 表结构转化为树结构
  const setTreeData = (arr) => {
    // 删除所有的children,以防止多次调用
    arr.forEach(function (item) {
      delete item.children
    })
    let map = {} //构建map
    arr.forEach((i) => {
      map[i.id] = i //构建以id为键 当前数据为值
    })
    let treeData = []
    arr.forEach((child) => {
      const mapItem = map[child.parentId] //判断当前数据的parentId是否存在map中
      if (mapItem) {
        //存在则表示当前数据不是最顶层的数据
        //注意： 这里的map中的数据是引用了arr的它的指向还是arr,当mapItem改变时arr也会改变，踩坑点
        ;(mapItem.children || (mapItem.children = [])).push(child) //这里判断mapItem中是否存在child
      } else {
        //不存在则是顶层数据
        child.top = true
        treeData.push(child)
      }
    })
    return treeData
  }
  defineExpose({
    open,
    close,
  })
</script>

<style lang="less" scoped>
  .icon-check {
    position: absolute;
    right: 8px;
    font-size: 12px;
    top: 10px;
    color: #3370ff;
  }

  :deep(.arco-tree-node-title:hover) {
    background-color: rgb(var(--primary-1));
  }
  :deep(.arco-tree-node-title-text) {
    padding-right: 20px;
    width: 460px;
    overflow-wrap: break-word;
  }

  .copy-wrapper {
    max-height: 470px;
    overflow: auto;
  }
</style>
